export const clearSessionStorage = () => {
  sessionStorage.removeItem("account");
  sessionStorage.removeItem("token");
  sessionStorage.removeItem("oss");
  sessionStorage.removeItem("router");
};

export const getToken = () => {
  return sessionStorage.getItem("token");
};

export const decodeBase64 = (data) => {
  return Buffer.from(data, "base64").toString();
};

export const encodeBase64 = (data) => {
  return Buffer.from(data).toString("base64");
};

export const formatBit = (limit) => {
  let size = "";
  if (limit < 0.1 * 1024) {
    size = limit.toFixed(2) + "B";
  } else if (limit < 0.1 * 1024 * 1024) {
    size = (limit / 1024).toFixed(2) + "KB";
  } else if (limit < 0.1 * 1024 * 1024 * 1024) {
    size = (limit / (1024 * 1024)).toFixed(2) + "MB";
  } else {
    size = (limit / (1024 * 1024 * 1024)).toFixed(2) + "GB";
  }

  let sizeStr = size + "";
  let index = sizeStr.indexOf(".");
  let dou = sizeStr.substr(index + 1, 2);
  if (dou === "00") {
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
  }
  return size;
};

const r = [];
export const getRouters = (router) => {
  router.map((i) => {
    if (i.menu) {
      getRouters(i.menu);
    } else {
      r.push({ component: i.component, path: i.path, name: i.name });
    }
  });
  return r;
};

/**
 * @description 获取localStorage
 * @param {String} key Storage名称
 * @return string
 */
export const localGet = (key) => {
  return window.localStorage.getItem(key);
};

/**
 * @description 存储localStorage
 * @param {String} key Storage名称
 * @param {Any} value Storage值
 * @return void
 */
export const localSet = (key, value) => {
  typeof value === "string"
    ? window.localStorage.setItem(key, value)
    : window.localStorage.setItem(key, JSON.stringify(value));
};

/**
 * @description 清除localStorage
 * @param {String} key Storage名称
 * @return void
 */
export const localRemove = (key) => {
  window.localStorage.removeItem(key);
};

/**
 * @description 清除所有localStorage
 * @return void
 */
export const localClear = () => {
  window.localStorage.clear();
};

export const loadView = (view) => {
  // 路由懒加载
  return (resolve) => require([`@/templates/${view}`], resolve);
};
//为权限路由异步添加组件
export const filterAsyncRouter = (routeList) => {
  routeList.forEach((item) => {
    item.component = loadView(item.component);
    if (item.children && item.children.length) {
      item.children = filterAsyncRouter(item.children);
    }
  });
  return routeList;
  // console.log('routeList', routeList)
  // return routeList
  // return routeList.filter((route) => {
  //   console.log('rrrrffffffff',route)
  //   if (route.component) {
  //     // 如果不是布局组件就只能是页面的引用了
  //     // 利用懒加载函数将实际页面赋值给它
  //     route.component = loadView(route.component);
  //     // 判断是否存在子路由，并递归调用自己
  //     if (route.children && route.children.length) {
  //       route.children = filterAsyncRouter(route.children);
  //     }
  //     return true;
  //   }
  // });
};

export const getPathById = (catalog, id, callback) => {
  // console.log("catalog", catalog);
  // console.log("id", id);
  // 定义变量保存当前结果路径
  const tempPath = [];
  try {
    const getNodePath = (node) => {
      tempPath.push(node.id);
      // 找到符合条件的节点，通过throw终止掉递归
      if (node.id === id) {
        const errorMessage = { message: "GOT IT!" };
        throw errorMessage;
      }
      if (node.childList && node.childList.length > 0) {
        for (let i = 0; i < node.childList.length; i++) {
          getNodePath(node.childList[i]);
        }
        // 当前节点的子节点遍历完依旧没找到，则删除路径中的该节点
        tempPath.pop();
      } else {
        // 找到叶子节点时，删除路径当中的该叶子节点
        tempPath.pop();
      }
    };
    getNodePath(catalog);
  } catch (e) {
    const result = tempPath;
    callback(result);
  }
};

const browserList = [
  {
    browser: 'Edge',
    versions: 79
  },
  {
    browser: 'Firefox',
    versions: 78
  },
  {
    browser: 'Chrome',
    versions: 86
  },
  {
    browser: 'Safari',
    versions: 12
  }
]


function getBrowserVersion(browserType, UserAgent) {
  let versions = '';

  switch (browserType) {
    case 'IE':
      versions = UserAgent.match(/(msie\s|trident.*rv:)([\w.]+)/)[2];
      break;
    case 'Chrome':
      for (let mt in navigator.mimeTypes) {
        //360 pc
        if (navigator.mimeTypes[mt]['type'] == 'application/360softmgrplugin') {
          browserType = '360';
        }
      }
      versions = UserAgent.match(/chrome\/([\d.]+)/)[1];
      break;

    case 'Firefox':
      versions = UserAgent.match(/firefox\/([\d.]+)/)[1];
      break;
    case 'Opera':
      versions = UserAgent.match(/opera\/([\d.]+)/)[1];
      break;
    case 'Safari':
      versions = UserAgent.match(/version\/([\d.]+)/)[1];
      break;
    case 'Edge':
      versions = UserAgent.match(/edge\/([\d.]+)/)[1];
      break;
    case 'QQBrowser':
      versions = UserAgent.match(/qqbrowser\/([\d.]+)/)[1];
      break;
  }

  return parseInt(versions);
}

function getBrowser() {
  const UserAgent = navigator.userAgent.toLowerCase();
  const browserInfo = {};

  const browserObj = {
    IE: window.ActiveXObject || "ActiveXObject" in window,
    Chrome: UserAgent.indexOf('chrome') > -1 && UserAgent.indexOf('safari') > -1,
    Firefox: UserAgent.indexOf('firefox') > -1,
    Opera: UserAgent.indexOf('opera') > -1,
    Safari: UserAgent.indexOf('safari') > -1 && UserAgent.indexOf('chrome') == -1,
    Edge: UserAgent.indexOf('edge') > -1,
    QQBrowser: /qqbrowser/.test(UserAgent),
    WeixinBrowser: /MicroMessenger/i.test(UserAgent)
  };

  for (let key in browserObj) {
    if (browserObj.hasOwnProperty(key) && browserObj[key]) {
      browserInfo.browser = key;
      browserInfo.versions = getBrowserVersion(key, UserAgent);
      break
    }
  }

  return browserInfo;
}

export function isUpgradeBrowser() {
  const { browser, versions } = getBrowser()

  for (const objKey of browserList) {
    if (objKey.browser === browser && versions < objKey.versions) {
      // 需要升级
      return {
        browser,
        versions,
        lowestVersions: objKey.versions,
        isUpdate: true
      }
    }
  }

  // 默认不需要升级
  return {
    browser,
    versions,
    isUpdate: false
  }
}
